import {
    defineAsyncComponent,
    h
} from "vue";
import Loading from "../components/Loading.vue";
import Error from "../components/Error.vue";
import "nprogress/nprogress.css";
import NProgress from 'nprogress';
NProgress.configure({
    trickleSpeed: 50,
    showSpinner: false,
})
export function delay(duration) {
    if (!duration) {
        duration = random(1000, 5000);
    }
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve();
        }, duration)
    })
}

export function random(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

export function getAsyncComponent(path) {
    return defineAsyncComponent({ // 定义异步组件, defineAsyncComponent 中传入的必须是一个 返回promise的函数, 动态的 import 就是一个promise
        loader: async () => {
            await delay();
            if (Math.random() < 0.5) {
                throw new TypeError();
            }
            return import(path);
        },
        //当promise在pending时显示:
        loadingComponent: Loading,
        errorComponent: {
            render() {
                return h(Error, "出错了");
            },
        },
    });
}

export function getAsyncPage(path) {
    return defineAsyncComponent({ // 定义异步组件, defineAsyncComponent 中传入的必须是一个 返回promise的函数, 动态的 import 就是一个promise
        loader: async () => {
            NProgress.start();
            await delay();
            const comp = import(path);
            NProgress.done();
            return comp;
        },
        loadingComponent: Loading,
    });
}